"use client"

/**
 * 全局认证状态 Context
 * 确保所有组件共享同一个认证状态实例
 */

import { createContext, useContext, ReactNode } from 'react'
import { useAuth as useAuthHook } from '../hooks/use-auth'

// 从 use-auth hook 导出的类型
type AuthContextType = ReturnType<typeof useAuthHook>

const AuthContext = createContext<AuthContextType | undefined>(undefined)

/**
 * AuthProvider - 在应用根部包裹，提供全局认证状态
 */
export function AuthProvider({ children }: { children: ReactNode }) {
  const auth = useAuthHook()

  return <AuthContext.Provider value={auth}>{children}</AuthContext.Provider>
}

/**
 * useAuth - 在任何组件中使用，获取全局共享的认证状态
 */
export function useAuth() {
  const context = useContext(AuthContext)
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider')
  }
  return context
}
